
package Retourner;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.WebServiceRef;
import Webservices.DocumentServiceService;
import Webservices.IOException_Exception;

/**
 * Servlet pour retourner un document XML.
 * @author Valentin & David.
 */
@WebServlet(name = "RetournerXML", urlPatterns = {"/retournerXML"})
public class RetournerXML extends HttpServlet {
    @WebServiceRef(wsdlLocation = "WEB-INF/wsdl/DocumentServiceService.wsdl")
    private DocumentServiceService service;
    
    /**
     * Fonction pour récupérer (POST) les paramètres de la page web.
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            PrintWriter out = response.getWriter();
            
            // On récupère l'identifiant du document que l'on souhaite retourner.
            String identifiant = request.getParameter("identifiantRetourner");
            
            // On fait appel au WS.
            byte[] resultat = retourneDocument(Integer.parseInt(identifiant));
            
            if(resultat.length != 0){
                // On convertie le tableau de bytes reçu en un objet de type File.
                File fileRes = Utils.Commons.convertirBytes2File(resultat,"xml");
                
                // Le fichier (une fois "décodé") est automatiquement téléchargé.
                response.setContentType("application/force-download");
                response.setContentLength((int)fileRes.length());
                response.setHeader("Content-Transfer-Encoding", "binary");
                response.setHeader("Content-Disposition","attachment; filename=\"" + "document.xml");
                InputStream in = new FileInputStream(fileRes);
                BufferedInputStream bin = new BufferedInputStream(in);
                DataInputStream din = new DataInputStream(bin);
                // Permet de lire chaque Bytes.
                while(din.available() > 0){
                    out.print((char)din.read());
                }
            }else{
                // On redirige vers la page resultRetourner.jsp.
                request.getRequestDispatcher("/resultRetourner.jsp").forward(request, response);
            }
            
        } catch (IOException_Exception ex) {
            Logger.getLogger(RetournerXML.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    /**
     * Fonction du web service.
     * @param arg0 : identifiant du document.
     * @return
     * @throws IOException_Exception
     */
    private byte[] retourneDocument(int arg0) throws IOException_Exception {
        Webservices.DocumentService port = service.getDocumentServicePort();
        return port.retourneDocument(arg0);
    }
    
    
}
